﻿using UnityEditor;
using UnityEngine;

public class WallRegulator : MonoBehaviour
{
    [Tooltip("运行时的城墙实例")]
    public GameObject wallInstance;
    
    [Tooltip("运行时的普通建筑实例")]
    public GameObject buildingInstance;

    [Tooltip("城墙的Prefab路径")]
    public string wallPrefabPath;

    public void Apply()
    {
        ApplyInstance();
        ApplyPrefab();
    }

    private void ApplyInstance()
    {
        Adjust(this.wallInstance);
    }

    private void ApplyPrefab()
    {
    #if UNITY_EDITOR
        var go = PrefabUtility.LoadPrefabContents(wallPrefabPath);
        if (go == null)
        {
            Debug.LogError("gameObject is null at " + wallPrefabPath);
            return;
        }

        Adjust(go);
        PrefabUtility.SaveAsPrefabAsset(go, wallPrefabPath);
        PrefabUtility.UnloadPrefabContents(go);
    #endif
    }

    private void Adjust(GameObject go)
    {
        var colliderGo = go.transform.Find("citywallcollider");
        var t = this.transform;
        colliderGo.transform.localPosition = t.localPosition;
        colliderGo.transform.localEulerAngles = t.localEulerAngles;
        colliderGo.transform.localScale = Vector3.one;
        var c = colliderGo.GetComponent<BoxCollider>();
        c.size = t.localScale;

        var uiRoot = go.transform.Find("UIDummy");
        uiRoot.transform.localPosition = t.localPosition;
        uiRoot.transform.localEulerAngles = Vector3.zero;

        var s1 = wallInstance.transform.localScale;
        var s2 = buildingInstance.transform.localScale;
        uiRoot.transform.localScale = new Vector3(s2.x / s1.x, s2.y / s1.y, s2.z / s1.z);
    }
}
